import os
import re
import shutil
from collections import defaultdict
from datetime import datetime
from pprint import pprint

from openpyxl import load_workbook

from ExcelUtils import copy_sheet_with_images
from config import output_folder, teacher_name
from input import term
from parse import number_pattern

result = dict()
class_mapping = dict()  # 教学班与实际班级的映射
class_name_and_hour = dict()  # 课程与对应学时的映射

def get_num(s):
    m = number_pattern.search(s)
    if m:
        return m.group(1)
    return ''


def convert_data(total_lessons):

    for lesson in total_lessons:
        entry = []
        teach_class = lesson[9] # 教学班
        teach_type = '实践教学' if 'A' in teach_class else '理论教学'
        subkey = teach_class.replace('A','') # 课程编号为sub key
        date = lesson[1]# 日期
        # 日期调整为2025年7月6日
        date = date.strftime("%Y年%m月%d日")
        week = lesson[0]
        key = lesson[5] # 课程名为key
        address = lesson[8] # 上课地点
        if address == '': # 没有上课地点的为混合式教学
            teach_type = '混合式教学'
        m = re.search("(20.*班)", lesson[10])
        if m:
            teach_class = m.group(1)
            class_mapping[subkey] = teach_class
        student_num = get_num(lesson[11])
        period = lesson[3]
        copy_time = 1
        if '-' in period:
            head, tail = period.split('-')
            # 1-4 实际是2次课，需要copy一次lesson
            copy_time = (int(tail) - int(head)) // 2 + 1
        entry.append(date)
        entry.append(week)
        entry.append(address)
        entry.append(student_num)
        entry.append(teach_type)
        for i in range(copy_time):
            if key in result:
                if subkey in result.get(key):
                    result.get(key).get(subkey).append(entry)
                else:
                    result.get(key)[subkey] = [entry]
            else:
                result[key] = defaultdict(list)
                result.get(key)[subkey] = [entry]



def create_teach_cal(total_lessons, file='template/teach_cal_temp.xlsx'):
    convert_data(total_lessons)
    pprint(result)
    pprint(class_mapping)
    for key, data in result.items(): # 按课程分类建立 教学日历的excel
        outfile = os.path.join(output_folder, f'{teacher_name}_教学日历_{key}.xlsx')  # 教学日历_Mongo.xlsx
        shutil.copy(file, outfile)
        workbook = load_workbook(outfile)
        for subkey, entry in data.items():
            class_hour = str(len(entry))
            class_name_and_hour[key] = class_hour
            src_sheet = f'class-{class_hour}'
            if not src_sheet in workbook.sheetnames:
                if int(class_hour) > 24:
                    src_sheet = 'class-32'
                elif 16 < int(class_hour) < 24:
                    src_sheet = 'class-24'
                elif int(class_hour) < 16:
                    src_sheet = 'class-16'
            sheet = copy_sheet_with_images(workbook, src_sheet,subkey)

            sheet.cell(2,1).value = sheet.cell(2,1).value.replace('@class_name', key)
            sheet.cell(2, 4).value = sheet.cell(2, 4).value.replace('@class_num', subkey[:-3])
            sheet.cell(2,6).value = sheet.cell(2,6).value.replace('@term', term)
            sheet.cell(3,1).value = sheet.cell(3,1).value.replace('@teach_class', class_mapping.get(subkey, ''))
            sheet.cell(3,4).value = sheet.cell(3,4).value.replace('@teacher_name',teacher_name)
            # 写入数据
            start_row = 5
            index = 1
            for cell in entry:
                # 序号
                sheet.cell(start_row, 1).value = str(index)
                # # 周次
                # sheet.cell(start_row, 3).value = f'第{cell[1]}周'
                # 讲次
                sheet.cell(start_row, 2).value = f'第{str(index)}讲'
                # 学时
                sheet.cell(start_row, 3).value = '100分钟'
                # 教学内容 4
                # 授课地点
                sheet.cell(start_row, 5).value = cell[2]
                # 授课日期
                sheet.cell(start_row, 6).value = cell[0]
                # 学生人数
                sheet.cell(start_row, 7).value = cell[3]
                # 教学形式
                sheet.cell(start_row, 8).value = cell[4]
                start_row += 1
                index += 1
        # 删除模版sheet
        workbook.remove_sheet(workbook['class-16'])
        workbook.remove_sheet(workbook['class-24'])
        workbook.remove_sheet(workbook['class-32'])
        workbook.save(outfile)
        workbook.close()

